package cn.jdy.plugins.service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Dealer;
import cn.jdy.plugins.entity.Info;

/**
 * 经销商管理实现类
 */
@Service
@DependsOn({"infoService", "confService"})
@Transactional
public class DealerService extends BaseDao<Dealer> {
	@Autowired
	private InfoService infoService;
	@Autowired
	private ConfService confService;

	public Dealer queryById(String id) {
		return super.findOne("id", id, "status", "1");
	}

	/**
	 * 查询经销商信息
	 *
	 * @return
	 */
	public List<Dealer> query(Dealer entity) {
	  return query(entity, null, null);
	}

	/**
	 * 查询经销商信息
	 *
	 * @return
	 */
	public List<Dealer> query(Dealer entity, String fromDate, String toDate) {
	  DetachedCriteria dc = createFilter(entity,fromDate,toDate);
    /*dc.addOrder(Order.desc("createTime"));*/
    return super.find(dc,entity.getiDisplayStart(),entity.getiDisplayLength());
	}

	/**
	 * 首页：查询审核通过的商机(包括审核通过，下架和已删除)
	 *
	 * @return
	 */
	public Long count(Dealer entity, String fromDate, String toDate) {
	  DetachedCriteria dc = createFilter(entity,fromDate,toDate);
		return super.count(dc);
	}

	/**
	 * 拼装条件
	 *
	 * @param entity
	 * @param page
	 * @return
	 */
	private DetachedCriteria createFilter(Dealer entity, String fromDate, String toDate) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if(StringUtil.isNotEmpty(entity.getKeywords())) {
		  if(StringUtil.isNotEmpty(entity.getKeyType())) {
		    dc.add(Restrictions.like(entity.getKeyType(),"%"+entity.getKeywords().trim()+"%"));
		  }
		}
		if(StringUtil.isNotEmpty(entity.getStatus())) {
		  dc.add(Restrictions.eq("status", entity.getStatus()));
		}
		/*if(StringUtil.isNotEmpty(entity.getUserType())) {
		  dc.add(Restrictions.eq("userType", entity.getUserType()));
		}*/
		if(StringUtil.isNotEmpty(entity.getCompanyName())) {
			  dc.add(Restrictions.eq("companyName", entity.getCompanyName()));
		}
		
		/*if(fromDate != null && fromDate.length() > 0 && toDate != null && toDate.length() > 0){
		  dc.add(Restrictions.between("createTime", fromDate, toDate));
		}else if(fromDate != null && fromDate.length() > 0){
		  dc.add(Restrictions.gt("createTime", fromDate));
		}else if(toDate != null && toDate.length() > 0){
		  dc.add(Restrictions.lt("createTime", toDate));
		} */
		return dc;
	}

/*	public List<Dealer> queryByKeyword(String usertype, String keyword, String keyType, String fromDate, String toDate) {
		StringBuilder sql = new StringBuilder("select t2.id,userName,mobile,password,t2.email," +
				"signature,photo,birthday,sex,country,longitude,latitude,createTime,lastLoginDate," +
				"userType,status,approve,score,money,realname,cardNum,cardImgUrl,province,city," +
				"district,areaCode,telPhone,t2.companyName,job,personalLocation,companyLocation" +
				" from `company` t1 right join `member` t2 on t2.`id` = t1.`userid`");
		if(keyword != null && keyword.length() > 0) {
			sql.append(" where ");
			switch(keyType) {
				case "":
					sql.append(" INSTR(T2.username, '").append(keyword).append("')>0").append(" OR INSTR(T2.mobile, '").append(keyword).append("')>0");
					break;
				case "1":
					sql.append(" INSTR(T2.username, '").append(keyword).append("')>0");
					break;
				case "2":
					sql.append(" INSTR(T2.mobile, '").append(keyword).append("')>0");
					break;
			}
		}

		if(fromDate != null && fromDate.length() > 0) {
			sql.append(sql.indexOf("where") > 0 ? " AND " : " where ");
			sql.append(" createTime >= date_format('").append(fromDate).append("','%Y-%m-%d %H:%i:%s')");
		}

		if(toDate != null && toDate.length() > 0) {
			sql.append(sql.indexOf("where") > 0 ? " AND " : " where ");
			sql.append(" createTime <= date_format('").append(fromDate).append("','%Y-%m-%d %H:%i:%s')");
		}
		return super.em().createSQLQuery(sql.toString()).list();
	}*/


	/**
	 * 更新经销商信息
	 *
	 * @param id
	 * @return flag
	 * @throws SQLException
	 * @description:
	 */
	public boolean updateMoney(String id, Long confId) {
		if(id == null || id.length() == 0 || confId == null || confId == 0) return false;
		ConfValue confValue = confService.find(confId);
		if(confValue == null || confValue.getValue1() == null) return false;
		String[] value = confValue.getValue1().split(",");
		int singleValue = Integer.parseInt(value[0]);
		if(singleValue <= 0) return false;

		String context = confValue.getValue0();
		int jf = context.indexOf("积分");
		int sm = context.indexOf("S币");
		Dealer dealer = super.find(id);
		if(jf>-1 && sm>-1) {
			if(jf > sm) {
				dealer.setScore(dealer.getScore() + Integer.parseInt(value[1]));
				dealer.setMoney(dealer.getMoney() + Integer.parseInt(value[0]));
			}else {
				dealer.setScore(dealer.getScore() + Integer.parseInt(value[0]));
				dealer.setMoney(dealer.getMoney() + Integer.parseInt(value[1]));
			}
			context = context.replaceFirst("%d", value[0]).replaceFirst("%d", value[1]);
		}else if(jf > -1) {
			dealer.setScore(dealer.getScore() + singleValue);
			context = context.replaceFirst("%d", value[0]);
		}else if(sm > -1) {
			dealer.setMoney(dealer.getMoney() + singleValue);
			context = context.replaceFirst("%d", value[0]);
		}else return false;

		try {
		  super.update(dealer);
		  //如果奖励成功，则发送消息提醒用户
			Info info = new Info();
			info.setType("1");
			info.setTitle(confValue.getRemark());
			info.setContext(context);
			info.setUserid(id);
			infoService.saveOrUpd(info);
		} catch(Exception e) {
			BaseLog.e(getClass(), "发送'系统奖励S币'系统消息异常！", e);
		}
		return true;
	}

	/**
	 * 更新经销商信息
	 *
	 * @param id
	 * @return flag
	 * @throws SQLException
	 * @description:
	 */
	public void updateMoneyWithInfo(String id, int money, String title, String context) throws SQLException {
		if(id == null || id.length() == 0 || money <= 0){
		  return ;
		} 
		super.update(id, "money", money);
		Dealer dealer = super.find(id);
		dealer.setMoney(dealer.getMoney() + money);
		if(StringUtil.isNotEmpty(title)) {
			try {
			  super.update(dealer);
				Info info = new Info();
				info.setType("1");
				info.setTitle(title);
				info.setContext(context);
				info.setUserid(id);
				infoService.saveOrUpd(info);
			} catch(Exception e) {
				BaseLog.e(getClass(), "发送'系统奖励S币'系统消息异常！", e);
			}
		}
	}

	/**
	 * 更新经销商信息
	 *
	 * @param id
	 * @return flag
	 * @throws SQLException
	 * @description:
	 */
	public void updateLoginDate(String id) throws SQLException {
	  super.update(id, "lastlogindate", DateUtil.getCurrentTime());
	}

	/**
	 * 修改经销商手机号
	 *
	 * @param bo
	 * @return flag
	 * @description:
	 */
	public void updateMobile(Dealer bo) {
	  super.update(bo.getId(), "mobile", bo.getMobile());
	}

	/**
	 * 修改经销商头像
	 *
	 * @param bo
	 * @return flag
	 * @description:
	 */
	public void updateForeImg(Dealer bo) {
	  super.update(bo.getId(), "photo", bo.getPhoto());
	}

	/**
	 * 批量更新经销商信息
	 *
	 * @param ids
	 * @return flag
	 * @description:
	 */
	public String updateBatch(String ids, int type, String value) throws SQLException {
		String result = null;
		List<String> list = Arrays.asList(ids.split(","));
		for(String s : list) {
//			int id = Integer.parseInt(s);
			String id = s;
			switch(type) {
				case 1:
				  super.update(id, "money", Integer.parseInt(value));
					break;
				case 3:
					super.delete(id);
					break;
				case 4:
				  super.update(id, "status", "1");
					break;
				case 5:
				  super.update(id, "status", "0");
					break;
				case 6:
					if(super.update(id, "approve", "1")>0)
						this.updateMoney(s, GlobalConstant.SMONEY_APPROVED);
					break;
				case 7:
				  super.update(id, "approve", "2");
					break;
				case 8:
					result = String.valueOf(Math.random()).substring(2,8);
					super.update(id, "password", SafeUtil.md5(result).substring(8, 16));
					break;
				default:
					break;
			}
		}
		return result;
	}

	/**
	 * : 经销商管理密码重置
	 *
	 * @return Boolean
	 * @description: 经销商管理密码重置
	 * @author: wangbo
	 * @date: 2013-10-15 16:53
	 */
	public Boolean updResetPwd(Dealer entity) {
		return super.update(entity.getId(), "password", entity.getPassword())>0;
	}

	/**
	 * 根据用户名查找用户
	 *
	 * @param username
	 * @return
	 */
	public Dealer findMemberByUsername(String username) {
	  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
	  dc.add(Restrictions.or(Restrictions.eq("userName", username),Restrictions.eq("mobile", username)));
	  return super.findOne(dc);
	}


	/**
	 * 根据用户名查找用户
	 *
	 * @param username
	 * @return
	 */
	public int findcheckUsername(String username) {
		SQLQuery query = super.em().createSQLQuery("select count(1) from member m ,confvalue c  where m.username = ? or (c.typeid =16 and c.value0 = ?) or m.mobile = ?");
		query.setParameter(0, username);
		query.setParameter(1, username);
		query.setParameter(2, username);
		return Integer.parseInt(String.valueOf(query.uniqueResult()));
	}

	/**
	 * 根据用户名查找用户
	 *
	 * @param mobile
	 * @return
	 */
	public Long findcheckUsermobile(String mobile) {
	  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
	  dc.add(Restrictions.or(Restrictions.eq("userName",mobile),Restrictions.eq("mobile",mobile)));
	  return super.count(dc);
	}

	/**
	 * 保存用户
	 *
	 * @param Dealer
	 * @return
	 */
	public Dealer saveMember(Dealer member) {
		String pwd = member.getPassword();
		member.setPassword(SafeUtil.md5(pwd).substring(8, 16));
		member.setStatus("0");
		member.setPhoto("/images/no-img_mid_.jpg");
		member.setScore(0);
		member.setMoney(0);
		member.setCreateTime(DateUtil.getCurrentTime());
		member.setApprove("0");
		save(member);
		try {
			Info info = new Info();
			info.setType("1");
			info.setTitle("恭喜您注册成功！");
			info.setContext(confService.findConfVal(String.valueOf(GlobalConstant.TYPE_MSG), "reg_S"));
			info.setUserid(member.getId());
			infoService.saveOrUpd(info);
		} catch(Exception e) {
			BaseLog.e(getClass(), "forSaveRegisterMember", e);
		}
		return member;
	}

	/**
	 * 修改经销商密码
	 *
	 * @param id
	 * @param attr
	 * @param value
	 * @return
	 */
	public boolean updatepwd(String mobile, String password) {
	  SQLQuery query = super.em().createSQLQuery("update member set password = ? where mobile = ?");
	  query.setParameter(0, password);
	  query.setParameter(1, mobile);
	  return query.executeUpdate() > 0;
	}
	
	/**
	 * 公司的联系方式
	 * @return
	 */
  public String getMobile(){
    String sql = "select mobile from member where companyId = ?1 and userType=1";//公司类型
    SQLQuery query = super.em().createSQLQuery(sql);
    return (String)query.uniqueResult();
  }
}